package my.jwds.p93;

import java.util.ArrayList;
import java.util.List;

public class RestoreIpAddresses {
    public static void main(String[] args) {
        RestoreIpAddresses obj = new RestoreIpAddresses();
        System.out.println(obj.restoreIpAddresses("101023"));
    }

    public List<String> restoreIpAddresses(String s) {
        return restoreIpAddresses(s,0,new String[4],0);

    }


    public List<String> restoreIpAddresses(String s,int index,String[] values,int valIndex) {
        List<String> res = new ArrayList<>();
        int remain = values.length - valIndex;
        int remainStr = s.length() - index;
        if (remain >remainStr || remain*3 < remainStr){
            return res;
        }
        if (valIndex == values.length){
            res.add(join(values,"."));
            return res;
        }
        values[valIndex] = s.substring(index,index+1);
        res.addAll(restoreIpAddresses(s,index+1,values,valIndex+1));
        if (values[valIndex].equals("0"))return res;
        if (index+2 <= s.length()){
            values[valIndex] = s.substring(index,index+2);
            res.addAll(restoreIpAddresses(s,index+2,values,valIndex+1));
        }
        if (index+3 <= s.length()) {
            values[valIndex] = s.substring(index, index + 3);
            if (values[valIndex].compareTo("255") <= 0) {
                res.addAll(restoreIpAddresses(s, index + 3, values, valIndex + 1));
            }
        }
        return res;
    }

    public String join(String[] values,String delimiter){
        StringBuilder sb = new StringBuilder();
        for (String value : values) {
            sb.append(delimiter);
            sb.append(value);

        }
        return sb.substring(1);
    }
}
